package com.gujiangbo.defrewlock;

public class ReadWriteLockImpl implements ReadWriteLock {

    //定义全局对象锁
    private final Object MUTEX = new Object();

    //定义当前有多少个线程正在执行写入操作
    private int writingWriters = 0;

    //定义当前有多少个线程正在执行读取操作
    private int readingReaders = 0;

    //定义当前有多少个线程正在执行等待写入操作
    private int waitingWriters = 0;

    // read和write的偏好设置
    private boolean perferWriter;

    public ReadWriteLockImpl() {
        this(true);
    }

    public ReadWriteLockImpl(boolean perferWriter) {
        this.perferWriter = perferWriter;
    }

    @Override
    public Lock readLock() {
        return new ReadLock(this);
    }

    @Override
    public Lock writeLock() {
        return new WriteLock(this);
    }

    @Override
    public int getWritingWriters() {
        return this.writingWriters;
    }

    @Override
    public int getWaitingWriters() {
        return this.waitingWriters;
    }

    @Override
    public int getReadingReaders() {
        return readingReaders;
    }

    void incrementWritingWriters() {
        this.writingWriters++;
    }

    void incrementReadingReaders() {
        this.readingReaders++;
    }

    void incrementWaitingWriters() {
        this.waitingWriters++;
    }

    void decrementWritingWriters() {
        this.writingWriters--;
    }

    void decrementReadingReaders() {
        this.readingReaders--;
    }

    void decrementWaitingWriters() {
        this.waitingWriters--;
    }

    Object getMutex() {
        return this.MUTEX;
    }

    boolean getPerferWriter() {
        return this.perferWriter;
    }

    //设置偏好
    void changePerfer(boolean pergerWriter) {
        this.perferWriter = pergerWriter;
    }

}
